﻿using System.Collections.Generic;
using System.Linq;

namespace DL.AI.AIBT
{
    //优先选择器
    public class PrioritySelector : Selector
    {
        private List<BTNode> m_SortedChildren;

        public PrioritySelector(string name,int priority = 0) : base(name,priority)
        {
        }

        private List<BTNode> SortedChildren => m_SortedChildren ??= SortChildren();

        protected virtual List<BTNode> SortChildren() => Children.OrderByDescending(child => child.Priority).ToList();

        public override Status Process()
        {
            foreach (var child in SortedChildren)
            {
                switch (child.Process())
                {
                    case Status.Success:
                        return Status.Success;
                    case Status.Failure:
                        continue;
                    case Status.Running:
                        return Status.Running;
                }
            }
            Reset();
            return Status.Failure;
        }

        public override void Reset()
        {
            base.Reset();
            m_SortedChildren = null;
        }
    }
}